package config

import (
	"fmt"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
)

var CONFIG_FILE_NAME = fmt.Sprintf("/config")

const CONFIG_FILE_TYPE = ".yaml"

func getExecutePath() string {
	exePath, err := os.Executable()
	if err != nil {
		panic(err)
	}
	// 获取可执行文件所在的目录路径
	exeDir := filepath.Dir(exePath)
	return exeDir
}

func init() {
	executePath := getExecutePath()
	configFilePath := executePath + CONFIG_FILE_NAME + CONFIG_FILE_TYPE
	viper.SetConfigType("yml")
	viper.SetConfigFile(configFilePath)

	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	// 读取不同环境的配置
	if viper.GetString("profile-active") != "" {
		configFilePath = executePath + CONFIG_FILE_NAME + "-" + viper.GetString("profile-active") + CONFIG_FILE_TYPE
		viper.SetConfigFile(configFilePath)
		err = viper.MergeInConfig()
		if err != nil {
			panic(err)
		}
	}
}

func Get(key string) interface{} {
	return viper.Get(key)
}

func GetString(key string) string {
	return viper.GetString(key)
}

func GetInt32(key string) int32 {
	return viper.GetInt32(key)
}

func GetInt64(key string) int64 {
	return viper.GetInt64(key)
}

func GetBool(key string) bool {
	return viper.GetBool(key)
}

func GetStringSlice(key string) []string {
	return viper.GetStringSlice(key)
}
